package algos;

import java.util.List;
import java.util.Map;

import ue.UE;
import eNodeB.ENodeB;
import eNodeB.RessourceBlock;

public class ProportionalFair extends AAlgos {

	public ProportionalFair(ENodeB eNodeB) {
		super(eNodeB);
	}

	@Override
	public void run() {
		eNodeB.freeBusyRessourceBlocks();
		eNodeB.freeMapRessourceBlocks();
		List<UE> users = eNodeB.getActualUE();
		if (!users.isEmpty()) {
			try {
				eNodeB.getSem().acquire();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}

			while (eNodeB.getPoolRessourceBlocksSize() != 0) {
				RessourceBlock rb = eNodeB.getFirstFreeRessourceBlock();
				if (rb != null) {
					double max = 0;
					UE maxUe = users.get(0);
					for (UE ue : users) {
						double throughPut = ue.getThroughPut(rb.getId());

						double averageThroughPut = ue.getAverageThroughput(
								ue.getMAC(), rb.getId());

						double ratio = throughPut / averageThroughPut;
						if (ratio > max) {

							max = ratio;
							maxUe = ue;

						}

					}
					Map<Integer, Integer> nbDemandmap = maxUe
							.getMapThroughputDemand().get(maxUe.getMAC());
					Integer nb = nbDemandmap.get(rb.getId());
					nb = nbDemandmap.get(rb.getId());
					nb++;
					nbDemandmap.put(rb.getId(), nb);
					Map<Integer, Double> avg = maxUe.getMapAverageThroughput()
							.get(maxUe.getMAC());
					double davg = maxUe.getAverageThroughput(maxUe.getMAC(),
							rb.getId())
							+ maxUe.getThroughPut(rb.getId());
					avg.put(rb.getId(), davg);
					maxUe.getMapAverageThroughput().put(maxUe.getMAC(), avg);
					schedule(maxUe, rb);
				}

			}
			eNodeB.getSem().release();
		}
	}
}
